package com.cd.university.config.security.validate;

import com.cd.university.config.security.properties.SecurityConstants;
import com.cd.university.config.security.properties.SecurityProperties;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @author 陈栋
 * @create 2021/9/4 11:14
 */
@Component("validateCodeFilter")
public class ValidateCodeFilter extends OncePerRequestFilter implements InitializingBean {

    /**
     * 登陆失败时调用的处理器
     */
    @Autowired
    private AuthenticationFailureHandler cdAuthenticationFailureHandler;

    /**
     * 系统配置信息
     */
    @Autowired
    private SecurityProperties securityProperties;

    /**
     * 存放所有需要校验的验证码的url
     * 这些url将会使用自定义的过滤器
     */
    private Map<String ,ValidateCodeType> urlMap = new HashMap<>();

    @Autowired
    private ValidateCodeProcessorHolder validateCodeProcessorHolder;

    /**
     * 用于将urls转义，例如/user/*代表url是user下的所有接口
     */
    private AntPathMatcher pathMatcher = new AntPathMatcher();

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest,
                                    HttpServletResponse httpServletResponse,
                                    FilterChain filterChain) throws ServletException, IOException {
        ValidateCodeType validateCodeType = getValidateCodeType(httpServletRequest);
        // 如果枚举类型不为空说明需要进行验证
        if (validateCodeType!=null) {
            try {
                ValidateCodeProcessor processor = validateCodeProcessorHolder.findValidateCodeProcessor(validateCodeType);
                processor.validate(new ServletWebRequest(httpServletRequest, httpServletResponse));
            }catch (ValidateCodeException exception) {
                cdAuthenticationFailureHandler.onAuthenticationFailure(httpServletRequest,
                        httpServletResponse,exception);
                return;
            }
        }
        doFilter(httpServletRequest, httpServletResponse, filterChain);
    }

    @Override
    public void afterPropertiesSet() throws ServletException {
        super.afterPropertiesSet();

        // 放需要图形验证码的默认的请求url
        urlMap.put(SecurityConstants.DEFAULT_SIGN_IN_PROCESSING_URL_FORM, ValidateCodeType.IMAGE);
        // 放需要图形验证码的用户指定的url,这里的url就是从securityProperties中拿出的
        addUrlToMap(securityProperties.getCode().getImageCode().getUrls(), ValidateCodeType.IMAGE);

        // 放需要短信验证码的默认的请求url
        urlMap.put(SecurityConstants.DEFAULT_SIGN_IN_PROCESSING_URL_MOBILE, ValidateCodeType.SMS);
        // 放需要短信验证码的用户指定的url
        addUrlToMap(securityProperties.getCode().getSmsCode().getUrls(), ValidateCodeType.SMS);

        // 放需要邮件验证码默认的请求url
        urlMap.put(SecurityConstants.DEFAULT_SIGN_IN_PROCESSING_URL_EMAIL, ValidateCodeType.EMAIL);
        addUrlToMap(securityProperties.getCode().getEmailCode().getUrls(), ValidateCodeType.EMAIL);
    }

    /**
     * 将系统中配置的需要校验验证码的URL根据校验的类型放入map
     *
     * @param urlString securityProperties中的url
     * @param type 验证码类型
     */
    protected void addUrlToMap(String urlString, ValidateCodeType type) {
        if (StringUtils.isNotBlank(urlString)) {
            String[] urls = StringUtils.splitByWholeSeparatorPreserveAllTokens(urlString, ",");
            for (String url : urls) {
                urlMap.put(url, type);
            }
        }
    }

    /**
     * 匹配前端请求的url是否需要验证
     * @param request 前端请求
     * @return ValidateCode枚举类型
     */
    private ValidateCodeType getValidateCodeType(HttpServletRequest request) {
        ValidateCodeType result = null;

        // 如果是get请求直接忽略
        if (!StringUtils.equalsIgnoreCase(request.getMethod(),"get")) {
            Set<String> urls = urlMap.keySet();
            for (String url : urls) {
                if (pathMatcher.match(url, request.getRequestURI())) {
                    result = urlMap.get(url);
                }
            }
        }
        return result;
    }
}
